package com.itheima.utils;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author: lm
 * @date: 2019/11/1
 */
public class RASUtils {
    private static PublicKey pubKey;
    private static PrivateKey privKey;

    //初始化公钥,私钥
    static {
        try {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            //加密公钥
            String strpk = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJtjgScVHxaBK2cHz3yN9WxkKjKD0f3+CluECo4+19nlrcMZkcJfOdFTmnXRTSzNzUwIvKVhKj8uCyRmJLO13pUCAwEAAQ==";
            //解密私钥
            String strprivk = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAm2OBJxUfFoErZwfPfI31bGQqMoPR/f4KW4QKjj7X2eWtwxmRwl850VOaddFNLM3NTAi8pWEqPy4LJGYks7XelQIDAQABAkB+B+fB7jSnyR6N01zrdixfvKIpFJemfXyjG2aAVuI1vPqwvfWaOdnnkUka1CkKvXoAGeiWSi4Sp2e+r8fnJyhlAiEA1cTylmzY8DkHAA9PIdBMPu6oH/T0EFbEo2uR/0pZ8RcCIQC6FgvxSC/D+s/M2TtKmV1cCdthgMvIuAHxllt4k4xBMwIhAK2lUjmHKaHZcSpHRUx+W7EzRDbRUACFuy3Uj8AEsZL5AiAieSUbPOFEcDmA3JmEV2cZPuY6aO7Xr2cEx3MIomTwSwIgRtrgkCpzdLSSDmwo8N6EplVpTAHLXpCPAOYWO/nevdc=";

            X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decodeBase64(strpk.getBytes()));
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(strprivk.getBytes()));

            KeyFactory keyf = KeyFactory.getInstance("RSA", "BC");
            pubKey = keyf.generatePublic(pubX509);
            privKey = keyf.generatePrivate(priPKCS8);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * RSA加密
     */
    public static String encryptData(String data) {
        try {
            String encryptString = null;
            //公钥不为null,需要加密数据不为null且不为""
            if (pubKey != null && (data != null && !data.equals(""))) {
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.ENCRYPT_MODE, pubKey);
                byte[] dataToEncrypt = data.getBytes("utf-8");
                byte[] encryptedData = cipher.doFinal(dataToEncrypt);
                encryptString = Base64.encodeBase64String(encryptedData);
            }
            System.out.println("加密后字符串：encryptString=" + encryptString);
            return encryptString;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("加密失败!");
        }
        return null;
    }

    /**
     * RSA解密
     */
    public static String decryptData(String data) {
        try {
            String srcData = null;
            if (privKey != null && (data != null && !data.equals(""))) {
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.DECRYPT_MODE, privKey);
                byte[] descryptData = Base64.decodeBase64(data);
                byte[] descryptedData = cipher.doFinal(descryptData);
                srcData = new String(descryptedData, "utf-8");
            }
            System.out.println("解密后字符串：srcData=" + srcData);
            return srcData;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("解密失败!");
        }
        return null;
    }

    /**
     * 公钥私钥生成工具
     */
    public static void createKeyPairs() {
        try {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");
            generator.initialize(512, new SecureRandom());
            KeyPair pair = generator.generateKeyPair();
            PublicKey pubKey = pair.getPublic();
            PrivateKey privKey = pair.getPrivate();
            byte[] pk = pubKey.getEncoded();
            byte[] privk = privKey.getEncoded();
            String strpk = new String(Base64.encodeBase64(pk));
            String strprivk = new String(Base64.encodeBase64(privk));

            System.out.println("public: " + strpk);
            System.out.println("private: " + strprivk);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String s = encryptData("18511279942");
    }

    @Test
    public void test(){
        String s = decryptData("LbWJmdJsaSfAJ0Oj3KiBayLdv/NUA7gLUYeJAd/yJmuSu0d53pu8TSf0sK24Q1aQolkszkkjyd96J0FX972gEg==");
        System.out.println(s);
    }
}
